package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.converter.MachineConverters;
import org.dromara.system.domain.Brand;
import org.dromara.system.domain.ProductsLine;
import org.dromara.system.domain.SysUserMachine;
import org.dromara.system.domain.bo.ProductsLineBo;
import org.dromara.system.domain.vo.BrandVo;
import org.dromara.system.domain.vo.ProductsLineVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.ProductsLineMapper;
import org.dromara.system.service.IBrandService;
import org.dromara.system.service.IProductsLineService;
import org.dromara.system.service.ISysUserMachineService;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品线Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-14
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProductsLineServiceImpl extends ServiceImpl<ProductsLineMapper, ProductsLine> implements IProductsLineService {

    private final ISysUserService sysUserService;
    private final ISysUserMachineService sysUserMachineService;
    private final PermissionBaseService permissionBaseService;

    /**
     * 查询产品线
     *
     * @param id 主键
     * @return 产品线
     */
    @Override
    public ProductsLineVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询产品线列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品线分页列表
     */
    @Override
    public TableDataInfo<ProductsLineVo> queryPageList(ProductsLineBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<ProductsLineVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<ProductsLineVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的产品线列表
     *
     * @param bo 查询条件
     * @return 产品线列表
     */
    @Override
    public List<ProductsLineVo> queryList(ProductsLineBo bo) {
        LambdaQueryWrapper<ProductsLine> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ProductsLine> buildQueryWrapper(ProductsLineBo bo) {
        LambdaQueryWrapper<ProductsLine> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ProductsLine::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), ProductsLine::getCode, bo.getCode());
        lqw.eq(bo.getBrandId() != null, ProductsLine::getBrandId, bo.getBrandId());
        lqw.eq(StringUtils.isNotBlank(bo.getImage()), ProductsLine::getImage, bo.getImage());
        lqw.eq(bo.getStatus() != null, ProductsLine::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增产品线
     *
     * @param bo 产品线
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProductsLineBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())){
            bo.setUserId(LoginHelper.getUserId());
        }
        ProductsLine productsLine = MapstructUtils.convert(bo, ProductsLine.class);
        validEntityBeforeSave(productsLine);
        Long brandId = productsLine.getBrandId();
        IBrandService brandService = SpringUtil.getBean(IBrandService.class);
        Brand brand = brandService.getOne(Wrappers.<Brand>lambdaQuery().eq(Brand::getId, brandId));
        BusinessException.isNull(brand, "品牌不存在");
        boolean flag = baseMapper.insert(productsLine) > 0;
        if (flag) {
            bo.setId(productsLine.getId());
        }
        return flag;
    }

    /**
     * 修改产品线
     *
     * @param bo 产品线
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductsLineBo bo) {
        ProductsLine update = MapstructUtils.convert(bo, ProductsLine.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProductsLine entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品线信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<SysUserMachine> list = sysUserMachineService.lambdaQuery().in(SysUserMachine::getLineId, ids).list();
            BusinessException.isTrue(CollUtil.isNotEmpty(list), "产品线下有机器禁止删除！");
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<BrandVo> queryBrandProductLine() {
        SysUserVo sysUserVo = sysUserService.selectUserById(LoginHelper.getUserId());
        IBrandService brandService = SpringUtil.getBean(IBrandService.class);
        List<Brand> list = brandService.lambdaQuery().eq(Brand::getUserId, sysUserVo.getUserId()).list();
        if (CollUtil.isEmpty(list)) {
            return Lists.newArrayList();
        }
        List<Long> collect = list.stream().map(Brand::getId).collect(Collectors.toList());
        List<BrandVo> brandVolist = MachineConverters.INSTANCE.toBrandVoList(list);

        List<ProductsLine> productsLines = lambdaQuery().in(ProductsLine::getBrandId, collect).list();
        List<ProductsLineVo> ProductsLineVolist = MachineConverters.INSTANCE.toProductsLineVoList(productsLines);
        brandVolist.forEach(t -> {
            List<ProductsLineVo> productsLineVos = ProductsLineVolist.stream().filter(t1 -> ObjectUtil.equal(t1.getBrandId(), t.getId())).collect(Collectors.toList());
            t.setProductsLineVos(productsLineVos);
        });
        return brandVolist;
    }
}
